package com.dz.lm.service.business.impl;

import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Service;

import com.dz.lm.common.dto.ApplyProductDTO;
import com.dz.lm.common.exception.DaoException;
import com.dz.lm.common.exception.ServiceException;
import com.dz.lm.common.util.JPushUtils;
import com.dz.lm.service.AbstractService;
import com.dz.lm.service.business.ApplyProductService;
import com.google.common.collect.Maps;


@Service
public class ApplyProductServiceImpl extends AbstractService implements ApplyProductService{
	
	public Logger logger = LogManager.getLogger(getClass());
	
	@Resource(name="readApplyProductDao")
	private com.dz.lm.dao.business.read.ApplyProductDao readApplyProductDao;
	
	@Resource(name="readProductDao")
	private com.dz.lm.dao.product.read.ProductDao readProductDao;
	
	@Resource(name="readAgentProductDao")
	private com.dz.lm.dao.product.read.AgentProductDao readAgentProductDao;
	
	@Resource(name="writeApplyProductDao")
	private com.dz.lm.dao.business.write.ApplyProductDao writeApplyProductDao;
	
	@Resource(name="writeUserDao")
	private com.dz.lm.dao.user.write.UserDao writeUserDao;
	
	@Resource(name="writeReminderDao")
	private com.dz.lm.dao.reminder.write.ReminderDao writeReminderDao;
	
	@Resource(name="readLoginLogDao")
	private com.dz.lm.dao.log.read.LoginLogDao loginLogDao;
	
	@Override
	public List<ApplyProductDTO> ListApplyProduct() throws ServiceException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public ApplyProductDTO selectByPrimaryKey(Integer applyId) throws ServiceException {
		ApplyProductDTO  applyProductDTO = null;
		try {
			  applyProductDTO = readApplyProductDao.selectByPrimaryKey(applyId);
		} catch (DaoException e) {
			throw new ServiceException(e.getCause());
		}
		return applyProductDTO;
	}

	@Override
	public Map<String, Object> insert(Map<String, Object> param) throws ServiceException {
		Map<String, Object> retData = new HashMap<String, Object>();
		Map<String, Object> product = null;
		String type = "";
		Object createUserId = null;
		int count = 0;
		try {
	    	//用户发布的产品自己不能申请
			if (param.get("productId") != null && !"".equals(String.valueOf(param.get("productId")))) {
				count = readApplyProductDao.qryProductDeployUser(param);
			} else {
				Map<String, Object> cntMap = readApplyProductDao.qryAgentProductDeployUser(param);
				if (cntMap != null && !cntMap.isEmpty()) {
					count = Integer.valueOf(cntMap.get("cnt").toString());
				}
			}
			if (count > 0) {
				retData.put("result", "01");
				retData.put("message", "该产品为您发布的产品，暂不允许发布者申请！");
				return retData;
			}
			List<Map<String, Object>> applyProductList = readApplyProductDao.qryApplyProductInfo(param);
			for (Map<String, Object> applyProductInfo : applyProductList) {
				if (applyProductInfo != null && !applyProductInfo.isEmpty()) {
					if ("0".equals(applyProductInfo.get("state"))) {
						retData.put("result", "01");
						retData.put("message", "该产品您已申请，机构暂未处理，请内心等待！");
						return retData;
					} else {
						Timestamp createTime = (Timestamp) applyProductInfo.get("createTime");
						Long now = System.currentTimeMillis();
				    	Long time = createTime.getTime();
				    	//30天内
				    	time = time + 30 * 24 * 60l * 60l * 1000l;
				    	if (time > now) {
							retData.put("result", "01");
							retData.put("message", "为避免短期内申请重复，请确认本月内对该产品的申请状态！");
							return retData;
				    	}
					}
				}
			}
			count = writeApplyProductDao.insert(param);
			if (count == 1) {
				Map<String, Object> userInfo = readApplyProductDao.qryAgentOrCreateUserInfoByProductId(param);
				userInfo.put("orderCount", 1);
				writeUserDao.updateUserOrderCountByUserId(userInfo);
				retData.put("result", "00");
				retData.put("message", "产品申请成功，请随时关注申请状态！");
				
		    	Map<String, Object> insertParam = new HashMap<String, Object>();
				if (param.get("productId") != null && !"".equals(String.valueOf(param.get("productId")))) {
					product = readProductDao.qryProductInfoByProductId(param);
					createUserId = product.get("createUserId");
					type = "4";
				} else {
					product = readAgentProductDao.qryAgentProductInfoByProductId(param);
					if ("1".equals(product.get("agentClass"))) {
						createUserId = product.get("createUserId");
					} else if ("2".equals(product.get("agentClass"))) {
						createUserId = product.get("agentId");
					}
					type = "5";
				}
				Map<String, Object> applyInfo = readApplyProductDao.qryLatestApplyInfo(param);
		    	insertParam.put("userId", createUserId);
		    	insertParam.put("type", type);
		    	if (product.get("originalProductId") != null && !"".equals(product.get("originalProductId"))) {
		    		insertParam.put("productId", product.get("originalProductId"));
		    	}


		    	insertParam.put("applyId", applyInfo.get("applyId"));
		    	writeReminderDao.addReminder(insertParam);
		    	insertParam.put("platform", param.get("platform"));
		    	Runnable runable = new AsyncThread(insertParam);
		    	runable.run();
			} else {
				retData.put("result", "01");
				retData.put("message", "产品申请失败！");
			}
		} catch (DaoException e) {
			throw new ServiceException(e.getCause());
		}
		return retData;
	}
	/**
	 * 消息推送
	 */
	private void pushMessage(Map<String, Object> param) throws ServiceException {
		Map<String, Object> pushInfo = null;
		Map<String, String> map_jp = Maps.newHashMap();
		try {
			pushInfo = loginLogDao.qryPushIdByUserId(param);
			if (pushInfo == null || pushInfo.isEmpty() || pushInfo.get("pushId") == null || "".equals(pushInfo.get("pushId"))) {
				return;
			}
            String pushTitle = "【微介】订单处理提醒";
            String pushContent = "您有新的申请订单待受理，请注意查收";
			// 推送
			if ("Android".equals(param.get("platform")) || "wexin".equals(param.get("platform"))) {
				// jpush
				String deviceAndro = pushInfo.get("pushId") == null ? "" : pushInfo.get("pushId").toString();
				//push消息
//                JPushUtils.pushAndroidMessageByRegistrationID(pushTitle, pushContent, deviceAndro);
				JPushUtils.pushAndroidNotificationByRegistrationID(pushTitle, pushContent, new HashMap(), deviceAndro);
			} else {
				if(param.get("IOS") != null){
					String[] deviceIos = param.get("IOS").toString().split(",");
					JPushUtils.pushIosNotificationByRegistrationID(pushContent, map_jp, deviceIos);
				}
			}
            logger.info("消息推送成功");
		}
		catch (DaoException e) {
			logger.info("消息推送失败");
			throw new ServiceException(e.getCause());
		}
	}
	
	@Override
	public int delete(Map<String, Object> param) throws ServiceException {
		// TODO Auto-generated method stub
		return 0;
	}

	public class AsyncThread implements Runnable {
		private Map<String, Object> param;

		AsyncThread(Map<String, Object> param) {
			this.param = param;
		}
		@Override
		public void run() {
			try {
				pushMessage(param);
			} catch (ServiceException e) {
				e.printStackTrace();
			}
		}
	}
}
